package com.foreverwin.jzymes.job;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.jzymes.common.service.IProductionShiftService;
import com.foreverwin.jzymes.framework.quartz.domain.SysJob;
import com.foreverwin.jzymes.framework.quartz.domain.SysJobParam;
import com.foreverwin.jzymes.framework.quartz.service.ISysJobParamService;
import com.foreverwin.jzymes.framework.util.DateUtil;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ChangeShiftService {

    private Logger logger = LoggerFactory.getLogger( ChangeShiftService.class );

    @Autowired
    IProductionShiftService productionShiftService;
    @Autowired
    ISysJobParamService sysJobParamService;
    @Autowired
    JmsMessagingTemplate jmsTemplate;

    public void checkShift( SysJob job ){
        String site = job.getSite();
        String shift = productionShiftService.findShift( site, new Date() );

        SysJobParam queryParam = new SysJobParam();
        queryParam.setJobBo( job.getHandle() );
        queryParam.setParamName( "SHIFT" );
        List<SysJobParam> jobParamList = sysJobParamService.selectSysJobParamList( queryParam );

        logger.info( "当前班次为：" + shift );
        if( jobParamList.size() == 0 ){
            SysJobParam sysJobParam = new SysJobParam();
            sysJobParam.setHandle( UUID.randomUUID().toString() );
            sysJobParam.setJobBo( job.getHandle() );
            sysJobParam.setParamName( "SHIFT" );
            sysJobParam.setParamValue( shift );
            sysJobParamService.insertSysJobParam( sysJobParam );
        }else if( !shift.equals( jobParamList.get( 0 ).getParamValue() ) ){
            for( SysJobParam sysJobParam : jobParamList ){
                sysJobParam.setParamValue( shift );
                sysJobParamService.updateSysJobParam( sysJobParam );
            }

            /**发送换班指令*/
            JSONObject message = new JSONObject();
            message.put( "MESSAGE_TYPE", "MES_CHANGE_SHIFT_COMMAND" );
            message.put( "SHIFT", shift  );
            message.put( "SEND_TIME", DateUtil.format( new Date(), "yyyy-MM-dd HH:mm:ss.SSS" ) );
            ActiveMQTopic topic = new ActiveMQTopic( "MES_CHANGE_SHIFT_COMMAND" );
            jmsTemplate.convertAndSend( topic, message.toString() );

            logger.info( "发送换班指令到EAP:" + message.toString() );
        }
    }

}
